package cn.com.ksplatform.ui.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.io.StreamUtil;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.com.ksplatform.common.logger.Log;

@SuppressWarnings("all")
//@WebServlet(urlPatterns = { "/ui/resource/*" , "*.cache"})
public class ResourceServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 968216741289112154L;
	
	private Map mimes = null;
	private boolean inited = false;
	
	private synchronized void initMimes() throws DocumentException{
		if(mimes ==  null && inited == false){
			mimes = new HashMap();
			SAXReader reader = new SAXReader();
			Document doc = reader.read(ResourceServlet.class.getResourceAsStream("mime.xml"));
			Element root = doc.getRootElement();
			for (Iterator<Element> iter = root.elementIterator(); iter.hasNext();) {
				Element e = iter.next();
				mimes.put(e.element("extension").getText(), e.element("mime-type").getText());
			}
			Log.info("初始化mime完成");
			inited = true;
		}
	}
	
	
	/**
	 * 获取链接的后缀名
	 * 
	 * @return
	 */
	private String parseSuffix(String url) {
		int idx = url.lastIndexOf(".");
		return url.substring(idx+1);
	}
	
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if(inited == false){
			try {
				initMimes();
			} catch (DocumentException e) {
				e.printStackTrace();
			}
		}
		String url = request.getRequestURI();
		int len = url.lastIndexOf("ui/");
		url = url.substring(len + 3);
		InputStream ins = Thread.currentThread().getContextClassLoader()
				.getResourceAsStream(url);
		if (ins == null) {
			response.sendError(404);
			response.setStatus(404);
		} else {
			String suffix = parseSuffix(url);
			if(mimes.get(suffix) != null){
				response.setContentType(mimes.get(suffix).toString());
				StreamUtil.copy(ins, response.getOutputStream());
			}else{
				Log.error(url+"资源类型:"+suffix+"无法匹配");
				response.sendError(404);
				response.setStatus(404);
			}
			
			/*if (url.endsWith(".css")) {
				response.setContentType("text/css;charset=utf-8");
				StreamUtil.copy(ins, response.getOutputStream());
			} else if (url.endsWith(".html")) { 
				response.setContentType("text/html;charset=utf-8");
				StreamUtil.copy(ins, response.getOutputStream());
			}else if (url.endsWith(".js")) {
				response.setContentType("text/javascript;charset=utf-8");
				StreamUtil.copy(ins, response.getOutputStream());
			}else if (url.endsWith(".json")) {
				response.setContentType("application/json");
				StreamUtil.copy(ins, response.getOutputStream());
			} else if (url.endsWith(".swf")) {
				response.setContentType("application/x-shockwave-flash");
				StreamUtil.copy(ins, response.getOutputStream());
			}else if (url.endsWith(".jpg") || url.endsWith(".png")
					|| url.endsWith(".gif") || url.endsWith(".ico")) {
				StreamUtil.copy(ins, response.getOutputStream());
			}else if (url.endsWith(".woff") || url.endsWith(".woff2")) {
				response.setContentType("application/x-font-woff");
				StreamUtil.copy(ins, response.getOutputStream());
			}else if (url.endsWith(".ttf")) {
				response.setContentType("application/x-font-ttf");
				StreamUtil.copy(ins, response.getOutputStream());
			}*/
		}
	}
}
